// ex 11.4 test

#include <LiquidCrystal.h> // we need this library for the LCD commands
LiquidCrystal lcd(12,11,5,4,3,2);

int moption = 1;

int ReadEncoder()
// returns 1 for anti-clockwise; 0 for clockwise movement
// doesn't read button, as it can be treated as a normal button
// if the encoder is not being turned, the function will sit and wait
// until the user turns the encoder
{
  int rotate, Position, Position2;
  int isFwd = 0;
  Position = (digitalRead(5) * 2) + digitalRead(7);
  do
    // while the encoder isn't being turned, don't do anything
  {
    Position2=(digitalRead(5) * 2) + digitalRead(7);
  } 
  while (Position2 == Position);
  if (Position2 != Position)
  {
    int isFwd = ((Position == 0) && (Position2 == 1)) ||
      ((Position == 1) && (Position2 == 3)) ||
      ((Position == 3) && (Position2 == 2)) ||
      ((Position == 2) && (Position2 == 0));
    return isFwd;
  }  
  Position = Position2;
}


void dispmenu(int qq)
// display the menu options, selectable by using the knob
{
  if      (qq==1) {
    lcd.clear();  
    lcd.setCursor(0,0); 
    lcd.print("Show timer data"); 
  }
  else if (qq==2) {
    lcd.clear();  
    lcd.setCursor(0,0); 
    lcd.print("Set timer 1"); 
  }
  else if (qq=3) {
    lcd.clear();  
    lcd.setCursor(0,0); 
    lcd.print("Set timer 2"); 
  }
  else if (qq=4) {
    lcd.clear();  
    lcd.setCursor(0,0); 
    lcd.print("Timers on/off"); 
  }
  else if (qq=5) {
    lcd.clear();  
    lcd.setCursor(0,0); 
    lcd.print("Set time and day"); 
  }
  else if (qq=6) {
    lcd.clear();  
    lcd.setCursor(0,0); 
    lcd.print("exit menu"); 
  }
}


void mainmenu()
{
  // function to display and control the main menu
  int a = 0;
   lcd.clear();  
    lcd.setCursor(0,0); 
    lcd.print(" * Main Menu * "); 
   delay(200);
  moption=1;
  while (digitalRead(3)==LOW)    // while the button hasn't been pressed
  {
    a = ReadEncoder();
    if (a==1) // turned to the left
    {
      moption--;
      if (moption<1)
      {
        moption=1;
      }
    }
    a = ReadEncoder();
    if (a==0) // turned to the right
    {
      moption++;
      if (moption>6)
      {
        moption=6;
      }
    }
    dispmenu(moption);
  }
}

void setup()
{
    // need for encoder - rotary encoder input lines
  pinMode(7, INPUT); // encoder pin A
  digitalWrite(7, HIGH); 
  pinMode(5, INPUT); // encoder pin B
  digitalWrite(5, HIGH);
    pinMode(3, INPUT);
  digitalWrite(3, HIGH);
  // end need for encoder
    delay(1);
   lcd.clear();  
  
}


void loop()
{
 lcd.clear();  
    lcd.setCursor(0,0); 
    lcd.print("Doody"); 
    delay(100); // stop flicker

  if (digitalRead(3)==HIGH)    // if button pressed, go to menu
  {
    delay(200);
    mainmenu();
  }
 /*
 
  display screen as normal while the button is low
  when the button has been pressed call function mainmenu()
  
  check timers as usual
  
  */
}

